import React from 'react';
import axios from 'axios';
import {Button, Form, Row, Col, Select, Tag, Spin} from 'antd';
import {injectIntl} from 'react-intl';
import StatisticsBox from '../../components/box/statistics';
import G2 from '@antv/g2/lib/simple';
import DataSet from '@antv/data-set';
import moment from 'moment';
import StubPicker from '../../components/pickCity/StubPicker'
const FormItem = Form.Item;
const Option = Select.Option;
const createForm = Form.create;

class OperationReport extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            options: [],
            respParams: {},
            boxParams: [],
            AntV: {},
            loading: true
        }
    }

    componentWillMount() {
        this.fetchData();
    }

    componentDidMount() {
        this.setState({
            AntV: new G2.Chart({
                container: 'power',
                forceFit: true,
                height: 350
            }),
            AntV2: new G2.Chart({
                container: 'count',
                forceFit: true,
                height: 350
            }),
            AntV3: new G2.Chart({
                container: 'duration',
                forceFit: true,
                height: 350
            }),
            AntV4: new G2.Chart({
                container: 'Avail',
                forceFit: true,
                height: 350
            }),
            ds: new DataSet()
        })

    }


    fetchData = () => {
        this.setState({
            loading: true
        })
        const common = this.props.intl.messages.common;
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            if(values.stubGroupId){
                values.stubGroupId=values.stubGroupId.currency;
            }
            axios.post('/api/analysis/total/qry', {...values}).then(res => {
                if (res && res.data) {
                    this.setState({
                        respParams: res.data,
                        boxParams: [
                            {"num": res.data.todayOrder ? res.data.todayOrder.power : '0', "desc": common.charAmountDay},
                            {"num": res.data.todayOrder ? res.data.todayOrder.count : '0', "desc": common.charCountDay},
                            {
                                "num": res.data.totalOrder ? res.data.totalOrder.power : '0',
                                "desc": common.totalChargeAmount
                            },
                            {
                                "num": res.data.totalOrder ? res.data.totalOrder.count : '0',
                                "desc": common.totalChargeCount
                            },
                            {"num": res.data.acAvail + "%", "desc": common.ACAvailable},
                            {"num": res.data.dcAvail + "%", "desc": common.DCAvailable}
                        ]
                    })
                }
            })
            axios.all([axios.post(`/api/analysis/chargeThisMonthDaily/qry`, {...values}), axios.post(`/api/analysis/chargeLastMonthDaily/qry`, {...values})])
                .then(axios.spread((curMonth, lastMon) => {
                    this.setState({
                        loading: false
                    })
                    let curMonthList, lastMonList = [];
                    let thisMonth = moment().format('DD')
                    if (curMonth && curMonth.data) {
                        curMonthList = curMonth.data.map((item) => {
                            let data = item.dimDate.substr(item.dimDate.length - 2, 2);
                            let flag = parseInt(data, 10) > parseInt(thisMonth, 10);
                            return {
                                days: data,
                                [common.curMonthP]: flag ? undefined : item.power,
                                [common.curMonthC]: flag ? undefined : item.chargeCnt,
                                [common.curMonthT]: flag ? undefined : item.chargeTime,
                                [common.curMonthAvail]: flag ? undefined : item.chargeAvail
                            }
                        });
                    }
                    if (lastMon && lastMon.data) {
                        lastMonList = lastMon.data.map((item) => {
                            let data = item.dimDate.substr(item.dimDate.length - 2, 2);
                            return {
                                days: data,
                                [common.lastMonthP]: item.power,
                                [common.lastMonthC]: item.chargeCnt,
                                [common.lastMonthT]: item.chargeTime,
                                [common.lastMonthAvail]: item.chargeAvail
                            }
                        });
                    }

                    lastMonList.forEach((k, v) => {
                        k[common.curMonthP] = curMonthList[v] ? curMonthList[v][common.curMonthP] : undefined;
                        k[common.curMonthC] = curMonthList[v] ? curMonthList[v][common.curMonthC] : undefined;
                        k[common.curMonthT] = curMonthList[v] ? curMonthList[v][common.curMonthT] : undefined;
                        k[common.curMonthAvail] = curMonthList[v] ? curMonthList[v][common.curMonthAvail] : undefined;
                    });

                    console.log(lastMonList)
                    let dv = this.state.ds.createView().source(lastMonList);
                    dv.transform({
                        type: 'fold',
                        fields: [common.curMonthP, common.lastMonthP], // 展开字段集
                        key: 'name', // key字段
                        value: 'power' // value字段
                    });
                    console.log(`dv`, dv)
                    this.state.AntV.source(dv, {
                        days: {
                            range: [0, 1]
                        }
                    });
                    this.state.AntV.tooltip({
                        crosshairs: {
                            type: 'line'
                        }
                    });
                    this.state.AntV.axis('power', {
                        label: {
                            formatter: function formatter(val) {
                                return val + ' A';
                            }
                        },
                        title: {}
                    });
                    this.state.AntV.scale('power', {
                        alias: common.monthPTitle
                    });
                    this.state.AntV.line().position('days*power').color('name');
                    this.state.AntV.render();
                    //充电数
                    let count = this.state.ds.createView().source(lastMonList);
                    count.transform({
                        type: 'fold',
                        fields: [common.curMonthC, common.lastMonthC], // 展开字段集
                        key: 'name', // key字段
                        value: 'chargeCnt' // value字段
                    });
                    this.state.AntV2.source(count);
                    this.state.AntV2.tooltip({
                        crosshairs: {
                            type: 'line'
                        }
                    });
                    this.state.AntV2.axis('chargeCnt', {
                        label: {
                            formatter: function formatter(val) {
                                return val + ` ${common.count}`;
                            }
                        },
                        title: {}
                    });
                    this.state.AntV2.scale('chargeCnt', {
                        alias: common.monthCTitle,
                        type: 'linear'
                    });
                    this.state.AntV2.scale('days', {
                        range: [0, 1],
                    });
                    this.state.AntV2.line().position('days*chargeCnt').color('name');
                    this.state.AntV2.render();
                    //充电时长
                    let duration = this.state.ds.createView().source(lastMonList);
                    duration.transform({
                        type: 'fold',
                        fields: [common.curMonthT, common.lastMonthT], // 展开字段集
                        key: 'name', // key字段
                        value: 'chargeTime' // value字段
                    });
                    this.state.AntV3.source(duration, {
                        days: {
                            range: [0, 1]
                        }
                    });
                    this.state.AntV3.tooltip({
                        crosshairs: {
                            type: 'line'
                        }
                    });
                    this.state.AntV3.axis('chargeTime', {
                        label: {
                            formatter: function formatter(val) {
                                return val + ` ${common.min}`;
                            }
                        },
                        title: {}
                    });
                    this.state.AntV3.scale('chargeTime', {
                        alias: common.monthTTitle
                    });
                    this.state.AntV3.line().position('days*chargeTime').color('name');
                    this.state.AntV3.render();
                    //充电利用率
                    let Avail = this.state.ds.createView().source(lastMonList);
                    Avail.transform({
                        type: 'fold',
                        fields: [common.curMonthAvail, common.lastMonthAvail], // 展开字段集
                        key: 'name', // key字段
                        value: 'chargeAvail' // value字段
                    });
                    this.state.AntV4.source(Avail, {
                        days: {
                            range: [0, 1]
                        }
                    });
                    this.state.AntV4.tooltip({
                        crosshairs: {
                            type: 'line'
                        }
                    });
                    this.state.AntV4.axis('chargeAvail', {
                        label: {
                            formatter: function formatter(val) {
                                return val + ' %';
                            }
                        },
                        title: {}
                    });
                    this.state.AntV4.scale('chargeAvail', {
                        alias: common.monthAvailTitle
                    });
                    this.state.AntV4.line().position('days*chargeAvail').color('name');
                    this.state.AntV4.render();
                }));
        });
    }

    render() {
        const layout = {
            xl: {span: 5},
            xxl: {span: 4}
        }
        const AntvStyle = {
            width: `50%`,
            display: 'inline-block'
        }
        const common = this.props.intl.messages.common;
        // console.log('this.state.respParams', this.state.respParams)
        return (
            <div>
                <form form={this.props.form} className={'SC-form'}>
                    <Row gutter={24} style={{height: 39, lineHeight: '39px'}}>
                        <Col xl={6} xxl={3}>
                            <FormItem
                            >
                                {this.props.form.getFieldDecorator(`stubGroupId`,{initialValue: {currency:undefined}})(
                                    <StubPicker style={{maxWidth:190}} useType={true} url="/api/stubGroup/listForOption/addSettlement/qry" mode={true}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={3}>
                            <FormItem>
                                <Button type="primary" className="ant-btn-84"
                                        onClick={this.fetchData}>{common.search}</Button>
                            </FormItem>
                        </Col>
                        <Col {...layout}>
                            {common.sumOfDevices}:
                            <Tag>{this.state.respParams.stubCount ? this.state.respParams.stubCount.totalStubCount : 0}</Tag>
                        </Col>
                        <Col {...layout}>
                            {common.DCDevices}:
                            <Tag>{this.state.respParams.stubCount ? this.state.respParams.stubCount.DCStubCount : 0}</Tag>
                        </Col>
                        <Col {...layout}>
                            {common.ACDevices}:
                            <Tag>{this.state.respParams.stubCount ? this.state.respParams.stubCount.ACStubCount : 0}</Tag>
                        </Col>
                    </Row>
                </form>
                <div>
                    <StatisticsBox params={this.state.boxParams}/>
                    <Spin spinning={this.state.loading}>
                        <div id="power" style={AntvStyle}></div>
                        <div id="count" style={AntvStyle}></div>
                        <div id="duration" style={AntvStyle}></div>
                        <div id="Avail" style={AntvStyle}></div>
                    </Spin>
                </div>
            </div>
        )
    }
}

OperationReport = createForm()(OperationReport);
export default injectIntl(OperationReport)